<?php
/**
 * Created by PhpStorm.
 * User: clcw908
 * Date: 2017/1/3
 */
header("Content-Type: text/html; charset=UTF-8");
date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);
if (isset($_SERVER['REQUEST_URI'])) {
    die('error');
}

if (!defined('API_ROOT_PATH')) {
    define('API_ROOT_PATH', dirname(__FILE__));
}

require(API_ROOT_PATH . '/../inc/common.php');
require(API_ROOT_PATH . '/../../App/Common/Lib/Aliyun/OSS/sdk.class.php');
require(API_ROOT_PATH . '/../../App/AuctionCore/Common/PhpRedis.class.php');


//初始化数据库链接
/**
 * @return MysqliDb
 */
function init_db()
{
    $db = new MysqliDb ([
        'host' => MYSQLDB,
        'username' => MYSQLDB_USER,
        'password' => MYSQLDB_PWD,
        'db' => MYSQLDB_DATABASE,
        'port' => 3306,
        'prefix' => 'au_',
        'charset' => 'utf8'
    ]);
    return $db;
}


$endpoint = OSS_ENDPOINT;
$accessKeyId = OSS_ACCESS_ID;
$accesKeySecret = OSS_ACCESS_KEY;

$oss = get_oss_client($accessKeyId, $accesKeySecret, $endpoint);


while (true) {

    $db = get_mysqli_db();
    $redis = new Redis();
    $redis->connect(REDIS_HOST, REDIS_PORT, 1);
    $redis->select(0);
    $transferProcedures = $redis->lRange('admin:Procedures:transfer_procedures', 0, -1);

    if (!empty($transferProcedures)) {
        foreach ($transferProcedures as $key => $values) {
            $orderId = $values;
            $imgList = [];
            $imgList = $db->where('order_id', $orderId)->get('transfer_img');

            if (empty($imgList)) {
                continue;
            }

            $fileArr = [];
            $dirName = '';
            foreach ($imgList as $key => $value) {

                $imageUrl = trim($value['url']);
                $fileName = basename($imageUrl);
                $dirName = dirname($imageUrl);
                $options = array(
                    $oss::OSS_FILE_DOWNLOAD => "./" . $fileName,
                );
                $oss->get_object(OSS_BUCKET, $imageUrl, $options);
                $fileArr[] = $fileName;
            }

            if (!empty($fileArr)) {

                $name = '过户手续' . date('Y.m.d', time()) . '.zip';
                $zipName = './' . $name;

                $files = array('image.jpeg', 'text.txt', 'music.wav');
                //$zipname = 'enter_any_name_for_the_zipped_file.zip';
                $zip = new ZipArchive;
                $zip->open($zipName, ZipArchive::OVERWRITE);
                foreach ($fileArr as $file) {
                    $zip->addFile($file);
                }
                $zip->close();

                $zipPath = $dirName . DIRECTORY_SEPARATOR . $name; //压缩包地址
                $result = $oss->upload_file_by_file(OSS_BUCKET, $zipPath, $zipName);
                if (!$result) {
                    logUtil('上传压缩包失败');
                } else {
                    $delResult = @unlink($zipName);
                    if (!$delResult) {
                        logUtil("删除压缩包 $zipName 失败！");
                    }
                }
                $data = [
                    'zip_url' => $zipPath,
                ];
            } else {
                $data = [
                    'zip_url' => '',
                ];
            }
            $result = $db->where('order_id', $orderId)->update('transfer_log', $data);
            if (!$result) {
                logUtil("拍单 $orderId 更新过户数据失败！");
            }

            foreach ($fileArr as $key => $value) {
                $filePath = './' . $value;
                if (file_exists($filePath)) {
                    if (!@unlink($filePath)) {
                        logUtil("删除" . $value . "失败");
                    }
                }
            }
            $redis->lRem('admin:Procedures:transfer_procedures', $orderId, 0);
            echo $orderId . "\n";
        }
    }

    unset($db); //销毁 $db对象
    $redis->close();
    sleep(300);
}


function get_oss_client($accessKeyId, $accesKeySecret, $endpoint)
{
    $oss = new \ALIOSS($accessKeyId, $accesKeySecret, $endpoint);
    return $oss;
}

